<template>
  <div class="pest-detection-container">
    <!-- 左侧面板 -->
    <div class="left-panel">
      <!-- 图片上传区域 -->
      <div class="upload-card">
        <div class="card-header">
          <i class="el-icon-picture-outline"></i>
          <span>校园昆虫检测</span>
          <el-tooltip content="点击图片区域可重新上传" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </div>
        <div class="upload-area" @click="handleUploadClick">
          <div v-if="imageUrl" class="image-container" :style="{ backgroundImage: 'url(' + imageUrl + ')' }">
            <div class="overlay-text">点击重新上传</div>
          </div>
          <div v-else class="upload-placeholder">
            <i class="el-icon-upload"></i>
            <div>点击上传昆虫图片</div>
          </div>
          <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleFileChange" />
        </div>
      </div>

      <el-input
          style="width: 240px; margin-left: 5px"
          placeholder="请输入分类"
          v-model="params.category"
          clearable
          @clear="load"
      ></el-input>

      <el-button
          style="margin-left: 5px"
          type="primary"
          icon="el-icon-search"
          @click="load"
      >搜索</el-button>

      <el-button
          style="margin-left: 5px"
          type="warning"
          icon="el-icon-refresh"
          @click="reset"
      >重置</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" stripe row-key="id" style="width: 100%">
      <el-table-column label="编号" width="80">
        <template slot-scope="scope">
          {{ (params.pageNum - 1) * params.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="昆虫名称" min-width="160" />
      <el-table-column prop="category" label="分类" width="120" />

      <el-table-column prop="livingHabits" label="生活习性" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ fixField(scope.row.livingHabits) }}
        </template>
      </el-table-column>

      <el-table-column prop="controlMethods" label="防治方法" min-width="220" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ fixField(scope.row.controlMethods) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="mini"
              @click="viewDetail(scope.row.id)"
          >详情</el-button>

          <el-button
              type="primary"
              size="mini"
              @click="$router.push('/editPest?id=' + scope.row.id)"
          >编辑</el-button>

          <el-popconfirm
              style="margin-left: 8px"
              title="您确定删除这行数据吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px; text-align: right">
      <el-pagination
          background
          layout="prev, pager, next"
          :current-page="params.pageNum"
          :page-size="params.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
        :title="detail.title"
        :visible.sync="detail.visible"
        width="700px"
        top="5vh"
        :close-on-click-modal="false"
    >
      <el-form label-width="110px" v-if="detail.data">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="编号：">
              <span>{{ detail.data.id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称：">
              <span>{{ detail.data.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="分类：">
          <el-tag size="small" :type="getTagType(detail.data.category)">
            {{ detail.data.category || '暂无' }}
          </el-tag>
        </el-form-item>

        <!-- 图片展示区域 -->
        <el-form-item label="昆虫图片：">
          <div v-if="detail.data && detail.data.imageUrls && detail.data.imageUrls.length > 0" class="image-gallery">
            <div
                v-for="(img, index) in detail.data.imageUrls"
                :key="index"
                class="image-container"
                :style="{ backgroundImage: 'url(' + img + ')' }"
                @click="previewImage(img)">
              <div class="image-overlay">
                <i class="el-icon-view"></i>
                <div>点击查看大图</div>
              </div>
            </div>
          </div>
          <div v-else class="no-image">
            暂无图片
          </div>
        </el-form-item>

        <el-form-item label="基本信息：">
          <div class="pre-line">{{ detail.data.basicInformation || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="形态特征：">
          <div class="pre-line">{{ detail.data.morphologicalCharacteristics || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="生活习性：">
          <div class="pre-line">{{ detail.data.livingHabits || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="发生规律：">
          <div class="pre-line">{{ detail.data.occurrencePattern || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="危害特点：">
          <div class="pre-line">{{ detail.data.hazardCharacteristics || '暂无' }}</div>
        </el-form-item>

        <el-form-item label="防治方法：">
          <div class="pre-line">{{ detail.data.controlMethods || '暂无' }}</div>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="detail.visible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'InsectList',
  data() {
    return {
      imageUrl: '', // 添加图片URL数据属性
      tableData: [],
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        category: ''
      },
      detail: {
        visible: false,
        title: '',
        data: null
      }
    }
  },
  created() {
    this.load()
  },
  methods: {
    /* ---------- 数据 ---------- */
    load() {
      // 调用分页接口获取昆虫列表数据
      request.get('/pest/page', { params: this.params }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },
    reset() {
      this.params = { pageNum: 1, pageSize: 10, name: '', category: '' }
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum
      this.load()
    },
    /* ---------- 删除 ---------- */
    del(id) {
      request.delete('/pest/delete/' + id).then(res => {
        if (res.code === '200') {
          this.$message.success('删除成功')
          this.load()
        } else {
          this.$message.error(res.msg || '删除失败')
        }
      })
    },
    /* ---------- 详情 ---------- */
    viewDetail(id) {
      // 获取昆虫详情
      request.get(`/pest/${id}`).then(res => {
        if (res.code === '200') {
          this.detail.data = res.data
          this.detail.title = `昆虫详情 - ${res.data.name}`
          this.detail.visible = true

          // 调用图片URL接口获取图片地址列表
          request.get(`/image/list/${id}`).then(imgRes => {
            let imageUrls = []
            if (imgRes.code === '200' && Array.isArray(imgRes.data)) {
              imageUrls = imgRes.data
            }
            // 将图片URL添加到详情数据中
            this.$set(this.detail.data, 'imageUrls', imageUrls)
          }).catch(() => {
            this.$set(this.detail.data, 'imageUrls', [])
          })
        } else {
          this.$message.error(res.msg || '获取详情失败')
        }
      }).catch(error => {
        console.error('获取昆虫详情失败:', error)
        this.$message.error('获取详情失败: ' + error.message)
      })
    },

    /* ---------- 图片处理 ---------- */
    handleUploadClick() {
      this.$refs.fileInput.click()
    },
    handleFileChange(event) {
      const file = event.target.files[0]
      if (file) {
        // 创建预览URL
        this.imageUrl = URL.createObjectURL(file)
        // 这里可以添加上传逻辑
      }
    },
    previewImage(imgUrl) {
      // 创建一个临时数组用于预览
      const previewList = [imgUrl + (imgUrl.includes('?') ? '&' : '?') + 'preview=true']
      // 这里可以使用Element UI的图片预览功能
      this.$alert(`<img src="${previewList[0]}" style="width: 100%; max-width: 500px;">`, '图片预览', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      })
    },

    /* ---------- 工具 ---------- */
    getTagType(category) {
      const map = {
        '蜱螨目': 'danger',
        '膜翅目': 'warning',
        '双翅目': 'danger',
        '缨翅目': 'success',
        '直翅目': 'danger',
        '同翅目/半翅目（刺吸类）': 'warning',
        '半翅目': 'danger',
        '鳞翅目': 'success',
        '鞘翅目': 'danger'
      }
      return map[category] || 'info'
    },
    fixField(val) {
      if (!val || val === 'null') return '暂无数据'
      return val
          .replace(/contro1Methods/g, 'controlMethods')
          .replace(/1ivingHabits/g, 'livingHabits')
    }
  }
}
</script>

<style scoped>
.pest-detection-container {
  display: flex;
  flex-direction: column;
}

.left-panel {
  margin-bottom: 20px;
}

.upload-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 15px;
}

.card-header i:first-child {
  margin-right: 8px;
  color: #409EFF;
}

.card-header i:last-child {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-placeholder {
  text-align: center;
  color: #909399;
}

.upload-placeholder i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.image-container {
  width: 10px;
  height: 10px;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  border-radius: 4px;
}

.image-container.small {
  width: 120px;
  height: 120px;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 4px;
}

.image-overlay i {
  font-size: 24px;
  margin-bottom: 5px;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.overlay-text {
  position: absolute;
  bottom: 10px;
  left: 0;
  width: 100%;
  text-align: center;
  color: white;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px;
  font-size: 14px;
}

.image-gallery {
  width: 40%;
  overflow: hidden;
  flex-wrap: wrap;
  gap: 15px;
}

.no-image {
  color: #999;
  font-style: italic;
}

.pre-line {
  white-space: pre-line;
}
</style>
